﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
public class Webtest : MonoBehaviour {
	private ClientWebSocket _clientWebsocket;
	private static int count = 0;
	void Start () {
		_clientWebsocket = new ClientWebSocket ();
		Task.Run (async () => {
			await StartConnect ();
		});
	}
	public async Task StartConnect () {

		await _clientWebsocket.ConnectAsync (new System.Uri ("ws://localhost:5000/super"), CancellationToken.None);
		print ("连接成功，准备开始接受消息");
		await ReceivedAsync ();
	}
	void Update () {
		if (Input.GetMouseButtonDown (0)) {
			Task.Run (async () => {
				await SendAsync ();
			});
		}
	}
	public async Task SendAsync () {
		byte[] bytes = Encoding.UTF8.GetBytes ("superman-<client>" + (count++).ToString ());
		await _clientWebsocket.SendAsync (new ArraySegment<byte> (bytes, 0, bytes.Length),
			System.Net.WebSockets.WebSocketMessageType.Text, true, CancellationToken.None);
		print ("发送成功");
	}
	public async Task ReceivedAsync () {
		while (!_clientWebsocket.CloseStatus.HasValue) {
			byte[] buffer = new byte[1024];
			ArraySegment<byte> arrays = new ArraySegment<byte> (buffer);
			await _clientWebsocket.ReceiveAsync (arrays, CancellationToken.None);
			print ("成功接收到内容为：" + Encoding.UTF8.GetString (arrays.Array));
		}
		await _clientWebsocket.CloseAsync (WebSocketCloseStatus.NormalClosure, "400", CancellationToken.None);
	}
	void OnApplicationQuit () {
		Task.Run (async () => {
			await _clientWebsocket.CloseAsync (WebSocketCloseStatus.NormalClosure, "455", CancellationToken.None);
			print ("关闭连接");
		});
	}
}